﻿using System;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic; 
using System.Data;
using TimeTravel.Extentions;
using TimeTravel.IData;
using TimeTravel.Components;

namespace TimeTravel.SqlServer  
{
    public class VisitorData : IVisitorData
    {
        #region Fields

        private static readonly SqlHelper DbHelper = new SqlHelper();
        private static readonly string[] Columns = { "[id]", "[clientip]", "[browser]", "[date]","[source]" };

        #endregion

        #region Implementation of IDataBase<VisitorInfo>

        /// <summary>
        /// 添加记录
        /// </summary>
        public int Add(VisitorInfo visitor)
        {
            if (visitor == null) return 0;
            var strSql = new StringBuilder();
            strSql.Append("insert into Visitor(");
            strSql.Append("[clientip],[browser],[date],[source],[useragent] ) ");
            strSql.Append(" values ");
            strSql.Append("(@clientip,@browser,@date,@source,@useragent) ;");
            strSql.Append("select @@IDENTITY;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@clientip", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@browser", SqlDbType.NVarChar, 100),
                                            new SqlParameter("@date", SqlDbType.Int),
                                            new SqlParameter("@source", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@useragent", SqlDbType.NVarChar, 200)
                                        };
            parameters[0].Value = visitor.ClientIP;
            parameters[1].Value = visitor.Browser;
            parameters[2].Value = visitor.Date;
            parameters[3].Value = visitor.Source;
            parameters[4].Value = visitor.UserAgent;
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString(), parameters);
            return result == null ? 0 : Convert.ToInt32(result);
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            if (id == 0) return;
            var strSql = new StringBuilder();
            strSql.Append("update Visitor set DeleteFlag = 1 ");
            strSql.Append("where [id] = @id;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@id", SqlDbType.Int)
                                        };
            parameters[0].Value = id;
            DbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
        }

        /// <summary>
        /// 更新记录（未实现）
        /// </summary>
        /// <param name="vistor"></param>
        public void Update(VisitorInfo vistor)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public IList<VisitorInfo> GetAll()
        {
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from Visitor ",String.Join(",",Columns));
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteObjectList(strSql.ToString(), DataReaderParser);
            return result.ToList();
        }

        /// <summary>
        /// 根据条件获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RecordSet<VisitorInfo> GetBySearch(PageQueryInfo query)
        {
            if(query == null) return new RecordSet<VisitorInfo>();
            return DbHelper.ExecutePaging("Visitor", query, DataReaderParser, Columns);
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public VisitorInfo GetOne(int id)
        {
            if (id == 0) return null;
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from Visitor ",String.Join(",",Columns));
            strSql.Append("where DeleteFlag = 0;");
            return DbHelper.ExecuteObject(CommandType.Text, strSql.ToString(), DataReaderParser);
        }

        /// <summary>
        /// 批量删除来访信息
        /// </summary>
        /// <param name="start">开始时间（时间戳格式）</param>
        /// <param name="end">结束时间（时间戳格式）</param>
        public void DeleteBatch(int start, int end)
        {
            if (start >= end) return;
            var strSql = new StringBuilder();
            strSql.Append("update Visitor set DeleteFlag = 1 ");
            strSql.Append("where [date]>=@start and [date]<=@end and DeleteFlag =0 ;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@start", SqlDbType.Int),
                                            new SqlParameter("@end", SqlDbType.Int)
                                        };
            parameters[0].Value = start;
            parameters[1].Value = end;
            DbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public int GetTotalCount()
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(id) from Visitor ");
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString());
            return result == null ? 0 : Convert.ToInt32(result);
        }

        #endregion

        #region BuildNavMenuObject

        /// <summary>
        /// 从DataReader中构建对象
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private VisitorInfo DataReaderParser(IDataReader reader)
        {
            var visitor = new VisitorInfo
                              {
                                  ID = reader.GetInt32("id"),
                                  Browser = reader.GetString("browser"),
                                  Source = reader.GetString("source"),
                                  Date = reader.GetInt32("date"),
                                  ClientIP = reader.GetString("clientip")
                              };
            return visitor;
        }

        #endregion
    }
}

